/**
 * 
 * 广州锐鹏计算机科技有限公司（www.ruipengkj.com）
 * 
 * 
 * Copyright (c) 2011-2012 RUIPENGKJ.Co.Ltd. All rights reserved.
 * 
 * */
package com.ruipengkj.component.comboBox;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.BevelBorder;
import javax.swing.plaf.basic.BasicComboPopup;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TCommodity;
import com.ruipengkj.bean.TStock;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.base.query.PageIndex;
import com.ruipengkj.commons.base.query.PageModel;
import com.ruipengkj.commons.base.query.PageView;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.WaitComponent;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.component.page.PageDelegale;
import com.ruipengkj.component.page.PagingComponent;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.factory.UIFactory;
import com.ruipengkj.service.TCommodityService;
import com.ruipengkj.service.TStockService;
/**
 * 说明： Combox主件的下拉为table
 * 
 * @Author：李智深
 * @Date：2012-4-1
 */
public class CommodityJComboBoxTabelPopup extends BasicComboPopup implements ActionListener,MouseListener,KeyListener,PageDelegale{
	private static final long serialVersionUID = 1L;
	
	private JButton queryButton;//查询按钮
	private JLabelJTextFieldComponent commodityTF; //编号
	private JLabelJTextFieldComponent commodityName; //商品名称
	
	private JTable table = null;
	private JScrollPane tableJsp;
	private BaseCommodityModel tableModel=null;
	private TCommodityService tCommodityService;
	private TStockService tStockService;
	private PagingComponent pagingComponent;//翻页组件
	private PageView<TCommodity> pageView;//翻页主键
	private PageView<TStock> pageViewStock;
	
	private  DefaultComboBoxModel defaultComboBoxModel =new DefaultComboBoxModel();
	private UIFactory uiFactory;
	private WaitComponent waitComponent;
	private TStore tStore = null;
	
	/**
	 * box:JComboBox实例
	 * tableModel:TableModel实例
	 * */
	public CommodityJComboBoxTabelPopup(JComboBox box, TStore tStore) {
		super(box);
		this.tStore = tStore;
		box.setModel(defaultComboBoxModel);
		tStockService = BuildSpringApplication.getInstance().getTStockServiceImpl();
		tCommodityService=BuildSpringApplication.getInstance().getTCommodityServiceImpl();
		uiFactory=UIFactory.getInstance();
		waitComponent=WaitComponent.getInstance();
		this.setLayout(new BorderLayout());
		Dimension dim=new Dimension(500, 300);
		this.setSize(300, 200);
		this.setPreferredSize(dim);
		this.setBackground(Color.WHITE);
		pageView=new PageView<TCommodity>();
		pageViewStock=new PageView<TStock>();
		
		table=uiFactory.createRPJTable(tableModel, null, this, 30, JLabel.CENTER);
//		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		
		
		tableJsp=new JScrollPane(table);
		pagingComponent=new PagingComponent();
		pagingComponent.setPageDelegale(this);
		topPanel();
		this.add(topPanel(),BorderLayout.NORTH);
		this.add(tableJsp,BorderLayout.CENTER);
		this.add(pagingComponent,BorderLayout.SOUTH);
		
		this.setBorder(BorderFactory.createLineBorder(Color.WHITE));
		this.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
		
		this.setCursor(Util.CURSOR_DEFAULT);
	}

	private JPanel topPanel(){
		JPanel top_jp = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_1).getImage());
		top_jp.setLayout(new FlowLayout(FlowLayout.LEFT));
		commodityTF=new JLabelJTextFieldComponent("商品编号：", 10);
		commodityName=new JLabelJTextFieldComponent("商品名称：", 10);
		queryButton=new JButton("查询");
		queryButton.addActionListener(this);
		top_jp.add(commodityTF);
		top_jp.add(commodityName);
		top_jp.add(queryButton);
		return top_jp;
	}

	@Override
	protected void firePropertyChange(String propertyName, Object oldValue,Object newValue) {
		if (propertyName.equals("visible")) {
			if (oldValue.equals(Boolean.FALSE)&& newValue.equals(Boolean.TRUE)) { // SHOW
				try {
					 tableModel=new BaseCommodityModel();
					 termQuery(1);
					 table.setModel(tableModel);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} else if (oldValue.equals(Boolean.TRUE)&& newValue.equals(Boolean.FALSE)) { // HIDE
			}
		}
		super.firePropertyChange(propertyName, oldValue, newValue);
	}

	public void hide(){
		
	}
	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getSource()==table){
			if(e.getClickCount()==2){
				int row=table.getSelectedRow();
				TCommodity comm=tableModel.getTCommodityList().get(row);
				if(comm!=null){
					if (comboBox.isEditable() && comboBox.getEditor() != null) {
						comboBox.configureEditor(comboBox.getEditor(), comm);
					}
					defaultComboBoxModel.addElement(comm);
					comboBox.setSelectedItem(comm);
//					comboBox.setPopupVisible(false);
					super.hide();
				}
				
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}
	//条件查询
	private void termQuery(int currentPage){
		TCommodity commodity=new TCommodity();
		commodity.setCommodityID(commodityTF.getText().getText().trim());
		commodity.setName(commodityName.getText().getText().trim());
		if(tStore != null) {
			TStock tStock = new TStock();
			tStock.setTStore(tStore);
			tStock.setTCommodity(commodity);
			tableJsp.getViewport().remove(table);
			tableJsp.getViewport().add(waitComponent);
			try {
				pageViewStock.setCurrentPage(currentPage);
				PageModel<TStock> pageModel=tStockService.getScrollService(pageViewStock.getFirstResult(), pageViewStock.getMaxResult(),tStock);
				pageViewStock.setPageModel(pageModel);
				pageViewStock.setPageIndex(PageIndex.getPageIndex(pageViewStock.getPageCode(), pageViewStock.getCurrentPage(), pageViewStock.getTotalPage()));
				if(pageModel!=null){
					tableJsp.getViewport().remove(waitComponent);
					tableJsp.getViewport().add(table);
					List<TCommodity> tCommodityList = new ArrayList<TCommodity>();
					for(int i = 0; i < pageModel.getResultList().size(); ++i) {
						TCommodity tCommodity = pageModel.getResultList().get(i).getTCommodity();
						tCommodityList.add(tCommodity);
						tCommodity.setStockNum(ApplicationContext.stockTotalNum(tCommodity.getCommodityID(), null));
					}
					tableModel.addList(tCommodityList);
					table.updateUI(); 
					pagingComponent.show();
				}else{
					//没有订单数据
					waitComponent.setText("不存在数据");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}
		tableJsp.getViewport().remove(table);
		tableJsp.getViewport().add(waitComponent);
		try {
			pageView.setCurrentPage(currentPage);
			PageModel<TCommodity> pageModel=tCommodityService.getScrollListService(pageView.getFirstResult(), pageView.getMaxResult(),commodity);
			pageView.setPageModel(pageModel);
			pageView.setPageIndex(PageIndex.getPageIndex(pageView.getPageCode(), pageView.getCurrentPage(), pageView.getTotalPage()));
			if(pageModel!=null){
				tableJsp.getViewport().remove(waitComponent);
				tableJsp.getViewport().add(table);
				for (int i = pageModel.getResultList().size()-1; i >= 0; --i) {
					TCommodity tCommodity = pageModel.getResultList().get(i);
					tCommodity.setStockNum(ApplicationContext.stockTotalNum(tCommodity.getCommodityID(), null));
				}
				tableModel.addList(pageModel.getResultList());
				table.updateUI(); 
				pagingComponent.show();
			}else{
				//没有订单数据
				waitComponent.setText("不存在数据");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
//	public void setInfoSales(int infoSales) {
//		this.infoSales = infoSales;
//	}
	@Override
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==queryButton){
			//查询
			this.termQuery(1);
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getSource()==commodityTF.getText()||e.getSource()==commodityName.getText()){
			//查询
			if(e.getKeyCode()==KeyEvent.VK_ENTER){
				queryButton.doClick();	
			}
		}
	}
	@Override
	public void keyReleased(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO Auto-generated method stub
		
	}
	/**--------------------------------翻页查询接口------------------------------------*/
	//首页
	@Override
	public void homePage() {
		this.termQuery(1);
	}
	//尾页
	@Override
	public void lastPage() {
		if (tStore != null) {
			this.termQuery((int)pageViewStock.getTotalPage());
			return;
		}
		this.termQuery((int)pageView.getTotalPage());
	}
	//下一页
	@Override
	public void nextPage() {
		if (tStore != null) {
			if(pageViewStock.getCurrentPage()>=pageViewStock.getTotalPage()){
				this.termQuery((int)pageViewStock.getTotalPage());
			}else{
				this.termQuery(pageViewStock.getCurrentPage()+1);
			}
			return;
		}
		if(pageView.getCurrentPage()>=pageView.getTotalPage()){
			this.termQuery((int)pageView.getTotalPage());
		}else{
			this.termQuery(pageView.getCurrentPage()+1);
		}
	}
	//上一页
	@Override
	public void prevPage() {
		if (tStore != null) {
			if(pageViewStock.getCurrentPage()<=1){
				this.termQuery(1);
			}else{
				this.termQuery(pageViewStock.getCurrentPage()-1);
			}
			return;
		}
		if(pageView.getCurrentPage()<=1){
			this.termQuery(1);
		}else{
			this.termQuery(pageView.getCurrentPage()-1);
		}
	}

	@Override
	public String getInfo() {
		if (tStore != null) {
			return "当前第 "+pageViewStock.getCurrentPage()+" 页/共 " +pageViewStock.getTotalPage()+" 页";
		}
		return "当前第 "+pageView.getCurrentPage()+" 页/共 " +pageView.getTotalPage()+" 页";
	}

}